﻿using FluentMigrator;
using FluentMigrator.Builders.Create.Table;

namespace Rubikev.Rockface.Database.Tables
{
   /// <summary>
   /// Abstract base class for creating tables
   /// </summary>
   public abstract class CreateTableMigration : Migration
   {
      /// <summary>
      /// The name of the table to create
      /// </summary>
      public abstract string TableName { get; }

      /// <summary>
      /// Creates the columns for the table
      /// </summary>
      /// <param name="table">The table to add the columns to</param>
      protected abstract void CreateColumns(ICreateTableWithColumnOrSchemaSyntax table);

      /// <summary>
      /// Creates any indexes for the table
      /// </summary>
      protected virtual void CreateIndexes()
      {
      }

      /// <summary>
      /// Creates the table
      /// </summary>
      public override void Up()
      {
         var table = Create.Table(TableName);
         CreateColumns(table);
         CreateIndexes();
      }

      /// <summary>
      /// Drops the table
      /// </summary>
      public override void Down()
      {
         Delete.Table(TableName);
      }

      /// <summary>
      /// Creates the index on the table, with the name IDX_<see cref="TableName"/>_<paramref name="columnName"/>
      /// </summary>
      /// <param name="columnName">The column to create the index on</param>
      public void CreateIndex(string columnName)
      {
         string indexName = string.Format("IDX_{0}_{1}", TableName, columnName);
         Create.Index(indexName).OnTable(TableName).OnColumn(columnName);
      }
   }
}
